import React, { useContext, useMemo, useRef, useState } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, Col, Row, Table, Tag, Tooltip } from 'antd';
import { cloneDeep, map } from 'lodash-es';

import CanvasRecord from '@/components/canvasRecord';
import drawMap, { PointVo } from '@/components/canvasRecord/drawMap';
import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import {
  proInspectionPointList,
  proInspectionPointSaveSort
} from '@/services/bizApi/shengchanxunjiandiweijiekou';
import type { DragEndEvent } from '@dnd-kit/core';
import { DndContext } from '@dnd-kit/core';
import type { SyntheticListenerMap } from '@dnd-kit/core/dist/hooks/utilities';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import {
  SortableContext,
  arrayMove,
  useSortable,
  verticalListSortingStrategy
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Icon } from '@iconify/react/dist/iconify.js';

import Edit, { EditRef } from './edit';

interface RowContextProps {
  setActivatorNodeRef?: (element: HTMLElement | null) => void;
  listeners?: SyntheticListenerMap;
}

const RowContext = React.createContext<RowContextProps>({});

const DragHandle: React.FC = () => {
  const { setActivatorNodeRef, listeners } = useContext(RowContext);
  return (
    <Button
      type="text"
      size="small"
      icon={<Icon icon="ri:draggable" />}
      style={{ cursor: 'move' }}
      ref={setActivatorNodeRef}
      {...listeners}
    />
  );
};

interface RowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  'data-row-key': string;
}

const RowDom: React.FC<RowProps> = (props) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    setActivatorNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({ id: props['data-row-key'] });

  const style: React.CSSProperties = {
    ...props.style,
    transform: CSS.Translate.toString(transform),
    transition,
    ...(isDragging ? { position: 'relative', zIndex: 1 } : {})
  };

  const contextValue = useMemo<RowContextProps>(
    () => ({ setActivatorNodeRef, listeners }),
    [setActivatorNodeRef, listeners]
  );

  return (
    <RowContext.Provider value={contextValue}>
      <tr {...props} ref={setNodeRef} style={style} {...attributes} />
    </RowContext.Provider>
  );
};

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProInspectionPointUpdateReq;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const [dataSource, setDataSource] = useState<PointVo[]>([]);

  const onDragEnd = ({ active, over }: DragEndEvent) => {
    console.log(active, over);

    if (active.id !== over?.id) {
      setDataSource((prevState) => {
        console.log('prevState:', prevState);
        const activeIndex = prevState.findIndex((record) => record.key === active?.id);
        const overIndex = prevState.findIndex((record) => record.key === over?.id);
        return arrayMove(prevState, activeIndex, overIndex);
      });
    }
  };

  const table = useAntdTable(
    async () => {
      const res = await proInspectionPointList({
        pointName: filter.getFieldValue('pointName') || ''
      });

      let backData: PointVo[] = [];
      backData = cloneDeep(res.data) as PointVo[];

      backData.forEach((item) => {
        const coordinate = drawMap.find((d) => d.name === item.pointName);
        if (coordinate) {
          item.x = (coordinate.x as number) || 0;
          item.y = coordinate.y || 0;
          item.key = item.pointId;
          item.name = item.pointName!;
        }
      });
      setDataSource((backData as PointVo[]) || []);

      return {
        list: backData || [],
        total: res.data?.length || 0,
        pagination: false
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const saveRecordLine = useRequest(
    async () => {
      const query = map(dataSource, 'pointId') as number[];
      await proInspectionPointSaveSort(query);
      store.app?.message.success('巡检路线保存成功');
    },
    {
      manual: true
    }
  );

  return (
    <>
      {/* 筛选 */}
      {/* <Filter onFinish={onSearch} form={filter} extra={<></>}>
        <Filter.Item name="pointName">
          <Select
            style={{
              width: 180
            }}
            placeholder="巡检点位"
            options={drawMap.map((item) => ({
              value: item.name,
              label: item.name
            }))}
          />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter> */}
      {/* end 筛选 */}

      <Row gutter={[16, 24]}>
        <Col span="10">
          {/* 表格 */}
          <DndContext modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
            <SortableContext
              items={dataSource
                .map((i) => i.key)
                .filter((key): key is string | number => key !== undefined)}
              strategy={verticalListSortingStrategy}
            >
              <Table
                size="small"
                columns={[
                  { key: 'sort', align: 'center', width: 30, render: () => <DragHandle /> },
                  {
                    title: '巡检顺序',
                    dataIndex: 'index',
                    align: 'center',
                    render: (_, row, index) => index + 1
                  },
                  {
                    title: '巡检点位',
                    dataIndex: 'pointName'
                  },
                  {
                    title: '巡检标准',
                    dataIndex: 'inspectionStandard',
                    width: 150,
                    render: (text) => (
                      <Tooltip placement="top" title={text} arrow={true}>
                        <div
                          style={{
                            width: '150px',
                            wordBreak: 'break-all',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap'
                          }}
                        >
                          {text}
                        </div>
                      </Tooltip>
                    ),
                    ellipsis: true
                  },
                  // {
                  //   title: '巡检顺序',
                  //   dataIndex: 'pointSort'
                  // },
                  {
                    title: '是否巡检',
                    dataIndex: 'status',
                    render: (status) => {
                      return status ? <Tag color="success">是</Tag> : <Tag color="red">否</Tag>;
                    }
                  },
                  {
                    title: '操作',
                    fixed: 'right',
                    align: 'center',
                    render: (_, row) => {
                      return (
                        <Text.Space>
                          {permission.check() && (
                            <Text
                              onClick={() => {
                                edit.current!.open({
                                  type: 'edit',
                                  rowData: row as BIZAPI.ProInspectionPointUpdateReq,
                                  onSuccess: () => {
                                    table.refresh();
                                  }
                                });
                              }}
                              type="primary"
                            >
                              编辑
                            </Text>
                          )}
                          {permission.check() && (
                            <Text
                              onClick={() => {
                                edit.current!.open({
                                  type: 'detail',
                                  rowData: row as BIZAPI.ProInspectionPointUpdateReq
                                });
                              }}
                              type="primary"
                            >
                              详情
                            </Text>
                          )}
                        </Text.Space>
                      );
                    }
                  }
                ]}
                scroll={{
                  x: 'max-content'
                }}
                rowKey="pointId"
                components={{ body: { row: RowDom } }}
                bordered
                {...table.tableProps}
                dataSource={dataSource}
                pagination={false}
              />
            </SortableContext>
          </DndContext>

          {/* end表格 */}
        </Col>
        <Col span="14" style={{ textAlign: 'center', overflow: 'hidden' }}>
          <CanvasRecord onClick={() => {}} dataSource={dataSource} />
          <div>
            <Button
              size="large"
              onClick={saveRecordLine.run}
              style={{ marginTop: '50px' }}
              type="primary"
            >
              保存巡检路线
            </Button>
          </div>
        </Col>
      </Row>

      <Edit ref={edit} />
    </>
  );
};

export default Page;
